package dyyx;

import java.util.HashMap;
import java.util.Map;

import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyCodeSource;

public class GroovyParseToInterfaceDemo {
	public static void main(String[] args) throws Exception {	
		System.out.println("GroovyParseToInterfaceDemo");	       
        //  转换成具体接口
        StringBuilder code = new StringBuilder();
        code.append("package dyyx;").append("\n");
        code.append("import java.time.LocalDateTime;").append("\n");
        code.append("import java.util.Map;").append("\n");
        code.append("public class TestIntfImpl implements dyyx.RunIntf {").append("\n");
        code.append("public Object execute(Map context) {").append("\n");
        // code.append("return LocalDateTime.now().toString();").append("\n");
        code.append("return 'hello,'+context.get('name');").append("\n");
        code.append("}").append("\n");
        code.append("}").append("\n");

        System.out.println(code);
        GroovyClassLoader loader = new GroovyClassLoader();
        Class groovyClass = loader.parseClass(code.toString());	
		System.out.println(groovyClass+","+System.identityHashCode(groovyClass));
		RunIntf intf = (RunIntf) groovyClass.newInstance();	
        Map map = new HashMap();
        map.put("name", "dyyx");
		System.out.println(intf.execute(map)); 
		
		// gcs.setCachable(false);  
		// 默认不缓存 ，每次都会创建新的 ，代码相同也不会缓存
		groovyClass = loader.parseClass(code.toString());	
		System.out.println(groovyClass+","+System.identityHashCode(groovyClass));
		
		
		System.out.println("\n\n");
		
		
		// cachable  true 
		// 相同的代码会缓存起来
		
		String codeBase = "/groovy/script";
		String fileName = "script1_" + System.currentTimeMillis() + Math.abs(code.toString().hashCode()) + ".groovy";
		GroovyCodeSource gcs = new GroovyCodeSource(code.toString(),fileName,codeBase);
		System.out.println(gcs);
		System.out.println(fileName);
		groovyClass = loader.parseClass(gcs);
		System.out.println(groovyClass+","+System.identityHashCode(groovyClass));
		System.out.println("\n\n");

		Thread.sleep(100);
		
		fileName = "script2_" + System.currentTimeMillis() + Math.abs(code.toString().hashCode()) + ".groovy";
		gcs = new GroovyCodeSource(code.toString(),fileName,codeBase);
		System.out.println(gcs);
		System.out.println(fileName);
		groovyClass = loader.parseClass(gcs);	
		System.out.println(groovyClass+","+System.identityHashCode(groovyClass));

		
	}		
}
